package org.csu.mypetstore.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.mypetstore.api.common.CommonResponse;
import org.csu.mypetstore.api.common.ResponseCode;
import org.csu.mypetstore.api.entity.*;
import org.csu.mypetstore.api.persistence.*;
import org.csu.mypetstore.api.service.AccountService;
import org.csu.mypetstore.api.service.ChatService;
import org.csu.mypetstore.api.vo.AccountVO;
import org.csu.mypetstore.api.vo.ChatUserVO;
import org.csu.mypetstore.api.vo.ContactDataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.csu.mypetstore.api.service.impl.AccountServiceImpl.entityToVO;

@Service("chatService")
public class ChatServiceImpl implements ChatService {
    @Autowired
    private ContactDataMapper contactDataMapper;
    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private BannerDataMapper bannerDataMapper;
    @Autowired
    private ProfileMapper profileMapper;
    @Autowired
    private AccountService accountService;

    @Override
    public CommonResponse<List<ChatUserVO>> findUsers(String keyword, String username) {
        List<ChatUserVO> responseData = new ArrayList<>();
        //条件封装
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("userid",keyword);
        List<Account> userList = accountMapper.selectList(queryWrapper);
        int len = userList.size();
        for(int i = 0;i < len;i++){
            Account tmpAccount = userList.get(i);
            if(!tmpAccount.getUsername().equals(username)){
                Profile profile = profileMapper.selectById(username);
                BannerData bannerData = bannerDataMapper.selectById(profile.getFavouriteCategoryId());
                AccountVO accountVO = entityToVO(tmpAccount,profile,bannerData);
                responseData.add(accountVO.toChatUserVO());
            }
        }
        if(responseData.isEmpty())
            return CommonResponse.createForSuccessMessage("未搜索到相关的用户");
        return CommonResponse.createForSuccess(responseData);
    }

    @Override
    public CommonResponse<List<ChatUserVO>> findGroups(String keyword, String username) {
        List<ChatUserVO> responseData = new ArrayList<>();
        //查询含有该关键词的群组
        QueryWrapper<Group> groupQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.like("groupid",keyword);
        List<Group> groups = groupMapper.selectList(groupQueryWrapper);

        int len = groups.size();
        for(int i = 0;i < len;i++){
            Group group = groups.get(i);
            ChatUserVO chatUserVO = new ChatUserVO();
            chatUserVO.setAvatar("");
            chatUserVO.setId(group.getGroupId());
            chatUserVO.setDisplayName(group.getGroupName());
            responseData.add(chatUserVO);
        }
        if(responseData.isEmpty())
            return CommonResponse.createForSuccessMessage("未搜索到相关的群组");
        return CommonResponse.createForSuccess(responseData);
    }

    @Override
    public CommonResponse<ContactDataVO> addUser(String friendName, String username) {
        //检查是否已经添加过这个好友了
        QueryWrapper<ContactData> queryWrapper = new QueryWrapper<ContactData>();
        queryWrapper.eq("userId", username);
        queryWrapper.eq("friendId",friendName);
        ContactData result = contactDataMapper.selectOne(queryWrapper);
        if(result != null)
            return CommonResponse.createForError(ResponseCode.HAD_ADD.getCode(), "您已经添加过该好友");

        ContactData contactData = new ContactData();
        contactData.setUserId(friendName);
        contactData.setFriendId(username);
        contactData.setDisplayName(username);
        contactData.setAvatar("");
        contactData.setToken(username.substring(0,1).toUpperCase());
        contactData.setUnread(0);
        contactData.setLastSendTime(new Date());
        contactData.setLastContent("");

        contactDataMapper.insert(contactData);

        contactData.setUserId(username);
        contactData.setFriendId(friendName);
        contactData.setDisplayName(friendName);
        contactData.setToken(friendName.substring(0,1).toUpperCase());



        contactDataMapper.insert(contactData);

        return CommonResponse.createForSuccess(entityToContactDataVO(contactData));
    }

    @Override
    public CommonResponse<ContactDataVO> enterGroup(String groupId, String username) {
        //检查是否已经添加过这个群组了
        QueryWrapper<ContactData> queryWrapper = new QueryWrapper<ContactData>();
        queryWrapper.eq("userId", username);
        queryWrapper.eq("friendId",groupId);
        ContactData result = contactDataMapper.selectOne(queryWrapper);
        if(result != null)
            return CommonResponse.createForError(ResponseCode.HAD_ADD.getCode(), "您已经添加过该群组");

        //先找到这个群
        Group group = groupMapper.selectById(groupId);
        //然后添加联系人
        ContactDataVO contactDataVO = insertGroupContact(username, group);

        return CommonResponse.createForSuccess(contactDataVO);
    }

    @Override
    public CommonResponse<ContactDataVO> createGroup(String groupId, String groupName, String header) {
        Account account = accountMapper.selectById(groupId);
        Group group = groupMapper.selectById(groupId);
        //这证明id已经被占用
        if(!(account == null && group == null))
            return CommonResponse.createForError("ID已经被占用");

        group = new Group();
        group.setGroupId(groupId);
        group.setGroupName(groupName);
        group.setHeader(header);

        //数据库添加一个群组
        groupMapper.insert(group);
        //为创建者添加一个联系人
        ContactDataVO contactDataVO = insertGroupContact(header, group);

        return CommonResponse.createForSuccess(contactDataVO);
    }

    @Override
    public CommonResponse<List<ContactDataVO>> getFriendsAndGroups(String username) {
        List<ContactDataVO> responseData = new ArrayList<>();

        QueryWrapper<ContactData> contactDataQueryWrapper = new QueryWrapper<ContactData>();
        contactDataQueryWrapper.eq("userid", username);
        List<ContactData> friendsAndGroups = contactDataMapper.selectList(contactDataQueryWrapper);
        int len = friendsAndGroups.size();
        for(int i = 0;i < len;i++){
            responseData.add(entityToContactDataVO(friendsAndGroups.get(i)));
        }

        if(responseData.isEmpty())
            return CommonResponse.createForSuccessMessage("没有好友或群组");
        return CommonResponse.createForSuccess(responseData);
    }

    public static ContactDataVO entityToContactDataVO(ContactData contactData){
        ContactDataVO contactDataVO = new ContactDataVO();

        contactDataVO.setId(contactData.getFriendId());
        contactDataVO.setDisplayName(contactData.getDisplayName());
        contactDataVO.setAvatar(contactData.getAvatar());
        contactDataVO.setIndex(contactData.getToken());
        contactDataVO.setUnread(contactData.getUnread());
        contactDataVO.setLastSendTime(contactData.getLastSendTime());
        contactDataVO.setLastContent(contactData.getLastContent());

        return contactDataVO;
    }

    //添加一个群组联系人，并返回VO
    public ContactDataVO insertGroupContact(String userId, Group group){
        ContactData contactData = new ContactData();
        contactData.setUserId(userId);
        contactData.setFriendId(group.getGroupId());
        contactData.setDisplayName(group.getGroupName());
        contactData.setAvatar("");
        contactData.setToken("群组");
        contactData.setUnread(0);
        contactData.setLastSendTime(new Date());
        contactData.setLastContent("");

        contactDataMapper.insert(contactData);

        return entityToContactDataVO(contactData);
    }

}